package javawdw.util.dlsoft.crypt;

import javawdw.util.crypt.Base64;
import javawdw.util.dlsoft.exception.UnKnownLinkException;
import javawdw.util.dlsoft.exception.UnValidLinkException;

/**
 * 下载链接
 * 
 * @author David
 * 
 */
public final class SoftLink {
	private String url;
	private LinkType linkType;

	/**
	 * 获得该下载链接URL地址
	 * 
	 * @return 返回得到的URL地址
	 */
	public String getUrl() {
		return this.url;
	}

	/**
	 * 根据给定的URL地址构造下载链接
	 * 
	 * @param url
	 *            给定的URL地址
	 */
	public SoftLink(String url) {
		this.url = url;
		this.linkType = discern(url);
	}

	/**
	 * 对给定链接解码
	 * 
	 * @return 返回解码后的下载链接
	 * @throws UnKnownLinkException
	 *             未知类型下载链接异常
	 * @throws UnValidLinkException
	 *             无效下载链接异常
	 */
	public TPLink decode() throws UnKnownLinkException, UnValidLinkException {
		String realLink = null;
		switch (this.linkType) {
		case UNKNOWN: {
			throw new UnKnownLinkException();
		}
		case HTTP: {
			return new TPLink(this.url);
		}
		default: {
			String base64Link = this.url.substring(this.linkType.getHead()
					.length());
			String disguiseLink = Base64.decode(base64Link);
			if (disguiseLink.startsWith(this.linkType.getStart())) {
				String temp = disguiseLink.substring(this.linkType.getStart()
						.length());
				int endIndex = temp.indexOf(this.linkType.getEnd());
				if (endIndex == -1) {
					throw new UnValidLinkException(this.linkType);
				} else {
					realLink = temp.substring(0, endIndex);
				}
			} else {
				throw new UnValidLinkException(this.linkType);
			}
			return new TPLink(realLink);
		}
		}
	}

	/**
	 * 解析给定链接的类型
	 * 
	 * @param link
	 *            给定链接
	 * @return 返回该链接类型
	 */
	public static LinkType discern(String link) {
		LinkType linkType = null;
		String temp = link.toUpperCase();
		if (temp.startsWith(LinkType.THUNDER.getHead())) {
			linkType = LinkType.THUNDER;
		} else if (temp.startsWith(LinkType.FLASHGET.getHead())) {
			linkType = LinkType.FLASHGET;
		} else if (temp.startsWith(LinkType.QQDL.getHead())) {
			linkType = LinkType.QQDL;
		} else if (temp.startsWith(LinkType.HTTP.getHead())) {
			linkType = LinkType.HTTP;
		} else {
			linkType = LinkType.UNKNOWN;
		}
		return linkType;
	}
}